package com.jaychen.eureka.client.eureka;

import com.jaychen.eureka.client.cache.LocalCache;
import com.jaychen.eureka.client.config.EurekaClientProperties;
import com.jaychen.eureka.client.http.HttpInvokerClient;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @Author Jay Chen
 * @Date 2020/10/26 13:12
 */
public class JayChenEurekaClient {

    private volatile HttpInvokerClient httpInvokerClient;

    private EurekaClientProperties eurekaClientProperties;

    /**
     * 心跳
     */
    private final Timer heart = new Timer("JayChen-Eureka-heart-Timer");

    private final Timer serviceList  = new Timer("JayChen-Eureka-serviceList-Timer");

    private volatile LocalCache localCache;

    public synchronized void initialized(EurekaClientProperties eurekaClientProperties) {
        this.eurekaClientProperties = eurekaClientProperties;
        if (localCache == null) {
            this.localCache = new LocalCache(this.eurekaClientProperties);
        }

        if (httpInvokerClient == null) {
            this.httpInvokerClient = new HttpInvokerClient(this.eurekaClientProperties, localCache);
        }
        initTask();
    }

    private void initTask() {
        heart.schedule(heartTask(), 1 * 1000L, 30 * 1000L);
        serviceList.schedule(register(), 1*1000L, 30 * 1000L);
    }

    private TimerTask register() {
        return new TimerTask() {
            @Override
            public void run() {
                httpInvokerClient.serviceList();
            }
        };
    }

    private TimerTask heartTask() {
        return new TimerTask() {
            @Override
            public void run() {
                httpInvokerClient.heart();
            }
        };
    }

}
